package com.nenglai.common.validator;

import com.nenglai.common.util.SpringUtil;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class UniqueValidator implements ConstraintValidator<Unique, String> {

    private Class<?> classz;
    private String field;
    private String beanName;

    public void initialize(Unique constraintAnnotation) {
        this.classz = constraintAnnotation.classz();
        this.field = constraintAnnotation.field();
        this.beanName = constraintAnnotation.classzName();
    }

    @SneakyThrows
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        DbUniqueExists obj = null;
        if (StringUtils.hasText(this.beanName)) {
            System.out.println(this.beanName);
            obj = (DbUniqueExists) SpringUtil.getBean(this.beanName);
        } else {
            obj = (DbUniqueExists) SpringUtil.getBean(this.classz);
        }
        return !obj.hasExists(this.field, s);
    }

}
